// pages/todoList/todoList.js
import $ from '../../utils/tool'
const app = getApp()
Page({
  data: {
    isShowModal: false,
    todoLists: null
  },
  onShow() {
    app.globalData.todoLists = $.storage.get('todoLists')
    let todoLists = Array.from(app.globalData.todoLists)
    todoLists.forEach((item, index) => {
      if ( item.isDone == true ) {
        todoLists.splice(index, 1)
      }
    })
    $.storage.set('todoLists', todoLists)
    todoLists = $.storage.get('todoLists') || []
    app.globalData.todoLists = todoLists
    this.setData({todoLists})
  },
  addToDo() {
    this.setData({ isShowModal: true })
  },
  modalCancel() {
    console.log('用户点击了取消')
    this.setData({ isShowModal: false })
  },
  // 确认增加待办事件
  modalConfirm(event) {
    let id = this.getId(2)
    let name = event.detail.name
    let time = event.detail.time
    let isDone = false
    let list = {id, name, time, isDone}
    let todoLists = app.globalData.todoLists || []
    todoLists.unshift(list) //新加的放在前面
    this.setData({todoLists}) //本地保存
    getApp().globalData.todoLists = todoLists //全局保存
    $.storage.set('todoLists', todoLists) // 放入缓存
    this.setData({ isShowModal: false })
  },
  // 动画
  toggle(e) {
    let animation = e.currentTarget.dataset.class;
    this.setData({ animation })
    setTimeout(() => {
      this.setData({
        animation: ''
      })
    }, 1000)
  },
  beginFocus(e){
    let todoLists = Array.from(this.data.todoLists)
    let choosedTodo = e.currentTarget.dataset.list
    wx.showModal({
      title: '是否要开始计时？',
      success: res => {
        if(res.confirm) {
          let todoIndex = -1
          todoLists.forEach((item, index) => {
            if ( item.id == choosedTodo.id ) { 
              item.isDone = true  //在onShow中在删除，这里删除会导致跳转错误
              todoIndex = index
            }
          })
          $.storage.set('todoLists', todoLists)
          getApp().globalData.isTodo = 1
          getApp().globalData.todoIndex = todoIndex
          wx.switchTab({
            url: '/pages/home/home',
          })
        }
      }
    })
  },
  // 获取随机ID，两位数
  getId(length){
    return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
  }
  
})